<template>
  <div class="add-product w-[100%] h-[100%">
    <ContentWrap :show-border="false">
      <el-affix :offset="114">
        <el-tabs
          type="card"
          v-model="activeName"
          class="tabs bg-#fff"
          @tab-change="clickTab(activeName)"
        >
          <template v-for="(item, index) in tabs" :key="index">
            <el-tab-pane
              :label="item.label"
              :name="item.name"
              v-if="(item.name == '3' && form.thaliFlag == 1) || item.name != '3'"
            >
              <template #label>
                <img
                  class="w-[16px] h-[16px]"
                  :src="activeName === item.name ? item.img1 : item.img2"
                  alt=""
                />
                <span class="ml-[4px]" :class="{ 'text-[#3721FF]': activeName === item.name }">
                  {{ item.label }}
                </span>
              </template>
            </el-tab-pane>
          </template>
        </el-tabs>
      </el-affix>
      <div class="w-[100%] h-[100%]">
        <SetBusiness
          v-show="activeName === '1'"
          ref="setBusinessRef"
          @update:form="handleUpdateSetBusiness"
          :form-data="form"
          @update:contact-info="updateContactInfo"
          :type="route.query.type"
        />
        <RuleAttribute
          v-show="activeName === '2'"
          ref="ruleAttributeRef"
          @update:form="updateRuleAttributes"
          @update:table-data="updateTableData"
          :form-data="form"
          :type="route.query.type"
          @isthaliFlag="updateThaliFlag"
        />
        <PackageSettings v-show="activeName === '3'" ref="packageSettingsRef" :activeName="activeName" :form-data="form" />
      </div>
    </ContentWrap>
    <ContentWrap :show-border="false">
      <div class="w-[100%] h-[100%] el-dia-btn text-center">
        <el-button type="default" @click="$router.go(-1)">取消</el-button>
        <el-button type="primary" :loading="loading" color="#3721FF" @click="submit(0)"
          >保存</el-button
        >
        <el-button type="primary" color="#3721FF" :loading="loading" @click="submit(2)">完成并预览</el-button>
      </div>
    </ContentWrap>
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: 'AddProduct' })
import SetBusiness from './basicInfo/index.vue'
import RuleAttribute from './ruleAttribute/index.vue'
import PackageSettings from './packageSettings/index.vue'
import { ProductApi } from '@/api/product/addProduct'
import router from '@/router'
import { object } from 'vue-types'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { deepCopy,throttle } from '@/utils'

const route = useRoute() // 路由信息
//const router = useRouter() // 路由对象
const isThaliFlag = ref()
const form = ref({})
const ruleAttributeRef = ref()
const setBusinessRef = ref()
const packageSettingsRef = ref()
const activeName = ref('1')
const loading = ref(false)
// 编辑查看详情等等
const handleGetProduct = async () => {
  await ProductApi.getProduct(route.query.id as string).then((res) => {
    form.value = JSON.parse(JSON.stringify(res)) // 回显
  })
}
// 基础信息
const handleUpdateSetBusiness = (rows: any) => {
  form.value = { ...form.value, ...rows }
  console.log(form.value, 'form.value7777');
  
}
// 规格属性
const updateRuleAttributeList = ref([])
const updateRuleAttributes = (rows: any) => {
  form.value = { ...form.value, ...rows }
  isThaliFlag.value = rows.thaliFlag
}
const updateThaliFlag = (rows: any) => {
  form.value.thaliFlag = rows.thaliFlag
  form.value.originalPrice = rows.originalPrice
  form.value.discountedPrice = rows.discountedPrice

}
// 规格属性2
const updateTableData = (rows: any) => {
  form.value.propertyList = rows
}
// 联系人信息列表
const contactInfoList = ref([])
const updateContactInfo = (rows: any) => {
  contactInfoList.value = rows
}
// 提交页面
const submit = throttle(async (type) => {
  loading.value = true
  // 根据传递的type判断是保存还是完成并预览
  if (route.query.type == '1' || route.query.type == '2') {
    form.value.type = 1
  } else if (route.query.type == '3') {
    form.value.type = 2
  }
  // 获取子页面传过来的方法
  let setBusiness = setBusinessRef.value?.updateSetBusiness()
  let ruleAttributeForms = ruleAttributeRef.value?.handleGetForms()
  form.value = { ...setBusiness, ...ruleAttributeForms, ...form.value }
  packageSettingsRef.value?.updatePackageSettings()
  let productThaliDOList = packageSettingsRef.value?.updatePackageSettings()
  form.value.productThaliDOList = productThaliDOList.filter((itm) => itm.name != '')
  if (form.value.picture) { // 图片处理
    if (Array.isArray(form.value.picture)) {
      form.value.picture = form.value?.picture.join(',')
    }
  }
  if (JSON.parse(JSON.stringify(form.value)).websiteId.length>0) { // 
    if (Array.isArray(JSON.parse(JSON.stringify(form.value)).websiteId)) {
      form.value.websiteId = form.value?.websiteId.join(',')
    }
  }
  if (JSON.parse(JSON.stringify(form.value)).websiteName.length>0) { // 
    if (Array.isArray(JSON.parse(JSON.stringify(form.value)).websiteName)) {
      form.value.websiteName = form.value?.websiteName.join(',')
    }
  }
  
  if (JSON.parse(JSON.stringify(form.value)).domain.length>0) { // 
    if (Array.isArray(JSON.parse(JSON.stringify(form.value)).domain)) {
      form.value.domain = form.value?.domain.join(',')
    }
  }
  if(form.value.tagFlag==0){
    form.value.tagValue=''
  }
  // 商品规格外文不能为空
  if(activeName.value == '2' && form.value.propertyList.some((item) => item.nameForeign == '')) {
    loading.value = false
    return ElMessage.error('商品规格外文不能为空')
  }
  // 提交

  console.log(type, 'type')
  console.log(route.query.id, 'route.query.id')
  console.log(form.value, 'form.value')
  if (route.query.id && activeName.value == '2' ) {
    if(form.value)
    // 基础信息编辑提交 因为有价格和折扣价
    ProductApi.updateProduct(form.value).then((res) => {
      // router.push({ name: 'ProductList' })
      router.push('/product/product/index')
      if (type == 2) {
          window.open(
            'https://' + 
            (Array.isArray(JSON.parse(JSON.stringify(form.value)).domain) ? form.value.domain[0] : form.value.domain?.split(',')[0]) + 
            '/#/product?id=' + route.query.id + '&tenantId=' + getTenantId(),
            '_blank'
          )
      }
      loading.value = false
    })
    loading.value = false
    // 规格属性编辑提交
    updateRuleAttributeList.value = ruleAttributeRef.value?.updateRuleAttribute()
    ProductApi.updateThaliList(updateRuleAttributeList.value, route.query.id).then((res) => {
      ElMessage.success('保存成功')
      // router.push({ name: 'ProductList' })
      router.push('/product/product/index')
      if (type == 2) {
          window.open(
            'https://' +
             (Array.isArray(JSON.parse(JSON.stringify(form.value)).domain) ? form.value.domain[0] : form.value.domain?.split(',')[0]) +
             '/#/product?id=' + route.query.id + '&tenantId=' + getTenantId(),
            '_blank'
          )
      }
      loading.value = false
    })
    loading.value = false
  } else if (route.query.id && activeName.value == '3') {
    // 基础信息编辑提交 因为有价格和折扣价
    ProductApi.updateProduct(form.value).then((res) => {
      ElMessage.success('保存成功')
      // router.push({ name: 'ProductList' })
      router.push('/product/product/index')
      if (type == 2) {
        window.open(
          'https://' + 
          (Array.isArray(JSON.parse(JSON.stringify(form.value)).domain) ? form.value.domain[0] : form.value.domain?.split(',')[0]) +
          '/#/product?id=' + route.query.id + '&tenantId=' + getTenantId(),
          '_blank'
        )
      }
      loading.value = false
    })
    // 套餐设置编辑提交
    packageSettingsRef.value?.updatePackageSettings()
    let productThaliDOList = packageSettingsRef.value?.updatePackageSettings()
    ProductApi.updateThali(productThaliDOList, route.query.id).then((res) => {
      loading.value = false
      // router.push({ name: 'ProductList' })
      router.push('/product/product/index')
     if (type == 2) {
        window.open(
          'https://' + 
          (Array.isArray(JSON.parse(JSON.stringify(form.value)).domain) ? form.value.domain[0] : form.value.domain?.split(',')[0]) + 
          '/#/product?id=' + route.query.id + '&tenantId=' + getTenantId(),
          '_blank'
        )
      }
    })
  } else {
    setBusinessRef.value?.getValidate().then((validate) => {
      if (validate) {
        if (form.value.template == '') {
          loading.value = false
          return ElMessage.error('请选择模板')
        }
        if (form.value?.originalPrice == null || form.value?.originalPrice == '') {
          loading.value = false
          activeName.value = '2'
          return ElMessage.error('请填写规格属性：原价不能为空！')
        }
        // 商品详情不能为空
        if (form.value?.detail == '') {
          loading.value = false
          return ElMessage.error('商品详情不能为空！')
        }
        if (!form.value.logisticsMethod || form.value.logisticsMethod == '') {
          ElMessage.error('请选择物流方式')
          loading.value = false
          return
        }
        form.value.picture = form.value?.picture ? form.value.picture.join(',') : [] //新增的时候单独处理图片
        form.value.websiteId = form.value?.websiteId ? form.value.websiteId.join(',') : ''//新增的时候单独处理适用站点
        form.value.websiteName = form.value?.websiteName ? form.value.websiteName.join(',') : ''//新增的时候单独处理适用站点名称
        // form.value.domain = form.value?.domain ? form.value.domain.join(',') : ''//新增的时候单独处理适用站点名称
        console.log(form.value.domain,'form.value.domain');
        
        try {
          if (route.query.id && route.query.id != '' && route.query.id != undefined) {
            // 基础信息编辑提交
            ProductApi.updateProduct(form.value).then((res) => {
              loading.value = false
              ElMessage.success('编辑成功')
              // router.push({ name: 'ProductList' })
              router.push('/product/product/index')
             if (type == 2) {
                window.open(
                  'https://' + (Array.isArray(JSON.parse(JSON.stringify(form.value)).domain) ? form.value.domain[0] : form.value.domain?.split(',')[0]) + '/#/product?id=' + route.query.id + '&tenantId=' + getTenantId(),
                  '_blank'
                )
              }
            })
          } else {
            ProductApi.createProduct(form.value).then((res) => {
              loading.value = false
              ElMessage.success('保存成功')
              // router.push({ name: 'ProductList' })
              router.push('/product/product/index')
             if (type == 2) {
                window.open(
                  'https://' + (Array.isArray(JSON.parse(JSON.stringify(form.value)).domain) ? form.value.domain[0] : form.value.domain?.split(',')[0]) + '/#/product?id=' + res + '&tenantId=' + getTenantId(),
                  '_blank'
                )
              }
            })
          }
          console.log('最终数据：', form.value)
        } catch (error) {
          console.log('error', error)
        }
      } else {
        ElMessage.error('请完善基础信息')
        loading.value = false
      }
    })
  }
  setTimeout(() => {
    loading.value = false
  }, 10000)
}
,1000) 

const tabs = ref([
  {
    label: '基础信息',
    isShow: true,
    name: '1',
    img1: 'https://img.alicdn.com/imgextra/i3/1034622205/O1CN012B3f2Q1S9wOlrK6sG_!!1034622205.png',
    img2: 'https://img.alicdn.com/imgextra/i3/1034622205/O1CN01dnWK6c1S9wOmc3795_!!1034622205.png'
  },
  {
    label: '规格属性',
    name: '2',
    isShow: true,
    img1: 'https://img.alicdn.com/imgextra/i4/1034622205/O1CN01ZyBBGz1S9wOlNhycM_!!1034622205.png',
    img2: 'https://img.alicdn.com/imgextra/i2/1034622205/O1CN01tOSDH11S9wOmu4DT4_!!1034622205.png'
  },
  {
    label: '套餐设置',
    name: '3',
    isShow: true,
    img1: 'https://img.alicdn.com/imgextra/i4/1034622205/O1CN01iHnRkU1S9wOnAjUp7_!!1034622205.png',
    img2: 'https://img.alicdn.com/imgextra/i2/1034622205/O1CN01nS0uS51S9wOmc3Rw7_!!1034622205.png'
  }
])
const clickTab = (val) => {
  if (val == '2' && route.query.id) {
    ruleAttributeRef.value?.getRuleAttribute(route.query.id as string)
    console.log(isThaliFlag.value, 'isThaliFlag.value')
  }
  if (val == '3' && route.query.id) {
    packageSettingsRef.value?.getPackageSettings(route.query.id as string)
  }
}
onMounted(async () => {
  if (route.query.id) {
    await handleGetProduct()
  }
})
</script>

<style scoped>
@import '@/styles/website.scss';
</style>
<style scoped lang="scss">
.tabs{
  height: 80px;
}
</style>
